package io.github.rascaler.dcenter.ws.handler;

import com.alibaba.fastjson.TypeReference;
import io.github.rascaler.dcenter.annotation.SocketPathMapping;
import io.github.rascaler.dcenter.context.ApplicationContextUtils;
import io.github.rascaler.dcenter.ws.message.SocketMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.yeauty.pojo.Session;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName HandlerDispatch
 * @Description TODO
 * @Author wurenqing
 * @Date 2023-11-28 14:37
 */

@Slf4j
@Component
public class SocketMessageDispatcher {
    private Map<String, SocketHandler<?>> handlerMapping = new HashMap<>();


    @PostConstruct
    public void init() {
        List<SocketHandler> handlers = ApplicationContextUtils.getBeansByClass(SocketHandler.class);
        for (SocketHandler handler : handlers) {
            SocketPathMapping annotation = handler.getClass().getAnnotation(SocketPathMapping.class);
            log.info("init socket handler：【{}】", handler.getClass());
            if (annotation != null) {
                String path = annotation.path();
                handlerMapping.put(path, handler);
            }
        }
    }

    public TypeReference getPayloadTypeReference(String path) {
        SocketHandler<?> handler = handlerMapping.get(path);
        return handler.getTypeReference();
    }


    public void dispatch(Session session, SocketMessage message) {
        SocketHandler<?> handler = handlerMapping.get(message.getPath());
        handler.execute(session, message);
    }
}
